/*
 *所有关于wsz_shebei类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*wsz_shebeiService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using DGZImp.Core.BaseProvider;
using DGZImp.Core.Extensions.AutofacManager;
using ATkg.BizAppProject.DomainModels;
using System.Linq;
using DGZImp.Core.Utilities;
using System.Linq.Expressions;
using DGZImp.Core.Extensions;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using ATkg.BizAppProject.IRepositories;
using DGZImp.Core.EFDbContext;
using DGZImp.Core.Exceptions;
using Newtonsoft.Json.Linq;
using static ATkg.BizAppProject.Services.daojiaoGDService;
using System.Globalization;
using DGZImp.Core.DbSqlSugar;
using static ATkg.BizAppProject.Services.cailiao_plan_dataService;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml.Drawing;
using MySql.Data.MySqlClient;
using System.Xml.Linq;

namespace ATkg.BizAppProject.Services
{
    public partial class wsz_shebeiService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly Iwsz_shebeiRepository _repository;//访问数据库
        public ISqlSugarClient Db = AutofacContainerModule.GetService<ServiceDbContext>()?.SqlSugarClient;
        //public ISqlSugarClient Db = AutofacContainerModule.GetService<ServiceDbContext>()?.SqlSugarClient;
        public AmesSyncService ames = AutofacContainerModule.GetService<AmesSyncService>();

        [ActivatorUtilitiesConstructor]
        public wsz_shebeiService(
            Iwsz_shebeiRepository dbRepository,
            IHttpContextAccessor httpContextAccessor
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }
        public async Task<object> GetMaterialProMes(string start_data = "", string end_data = "")
        {
            Console.WriteLine("进来了！！！");
            ames.userName = "duyang@atmcn.com";
            ames.password = "Du123456*";
            //ames.url = "http://10.7.1.9/jsonrpc";
            //ames.db = "prd0803";
            var isSingle = start_data.IsValuable();
            Console.WriteLine(start_data);
            var typeArray = new[] { "final" };

            var qDomain = new List<object> { };

            if (isSingle)
            {
                Console.WriteLine("DDDDDD");
                qDomain.Add(new List<object> { "date_stock_done", ">=", start_data });
                qDomain.Add(new List<object> { "date_stock_done", "<=", end_data });
                //Console.WriteLine(qDomain.ToArrayString);
            }
            //else
            //{
            //    qDomain.Add(new List<object> { "state", "=", "in_production" });
            //}

            var qFields = new List<string> {
                "id",
                "blank_weight"
            };
            var qPage = new
            {
                limit = 100000,
                offset = 0
            };

            var res = await ames.Get_stoke_("mrp.production.report.blank", qDomain, qFields, qPage);
            var r = (JArray)res["result"];
            Console.WriteLine(r.Count);
            Console.WriteLine(res);
            //float total_pro = 0;
            //for(int i = 0; i < r.Count; i++)
            //{
            //    total_pro += (float)r[i]["blank_weight"];
            //}
            //Console.WriteLine(total_pro);
            return new
            {
                rows = r,
                total = res.Count
            };
        }
        [SugarTable("wsz_shebei")] // 映射表名
        public class wsz_shebei
        {
            [SugarColumn(IsPrimaryKey = true)] // 主键标识（若存在）
            public string name { get; set; }
            public string category_id { get; set; }
            public string serial_no { get; set; }
            public string ccd_status { get; set; }
            public string mesid { get; set; }
            public string dj { get; set; }

        }
        public async Task<object> get_info_from_bfmes()
        {

            Console.WriteLine("进来了！！！");
            ames.userName = "duyang@atmcn.com";
            ames.password = "Du123456*";
            ames.url = "http://10.7.1.17/jsonrpc";
            ames.db = "antai";
            // 1. 构建domain条件树
            var domain1 = new List<object>
            {
                new List<object> { "department_id", "child_of", 55 }
            };
            // 2. 构建specification字段映射
            var qFields = new List<string> {
                "name",
                "category_id",
                "serial_no",
                "ccd_status",
                "id"
            };
            // 3. 组合最终结构category_id
            var result = new Dictionary<string, object>
            {
                { "domain", domain1 },
                { "fields", qFields }
            };
            var resp = await ames.Get_web_search_read("maintenance.equipment", result);
            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var record = (JArray)resp["result"]["records"];
            
            for (int i = 0; i < record.Count; i++)
            {
                var final_data_info_ = new List<wsz_shebei>();
                final_data_info_.Add(new wsz_shebei
                {
                    name = (string)record[i]["name"],
                    serial_no = (string)record[i]["serial_no"],
                    ccd_status = record[i]["ccd_status"].Type == JTokenType.Boolean ? null : (string)record[i]["ccd_status"],
                    mesid = (string)record[i]["id"],
                });
                var name = (string)record[i]["name"];
                int count1 = Db.Queryable<wsz_shebei>()
                    .Where(it => it.name == (string)name)
                    .Count();
                if (count1 == 0)
                {
                    await Db.DoInsertAsync<wsz_shebei>(final_data_info_);
                }
                else
                {
                    int rowsAffected1 = Db.Updateable<wsz_shebei>()
                        .SetColumns(it => new wsz_shebei
                        {
                            name = (string)record[i]["name"],
                            serial_no = (string)record[i]["serial_no"],
                            ccd_status = record[i]["ccd_status"].Type == JTokenType.Boolean ? null : (string)record[i]["ccd_status"],
                            mesid = (string)record[i]["id"],
                        })
                        .Where(it => it.name == (string)name) // 精确条件
                        .ExecuteCommand();
                }
            }
            return "成功";
        }

        public async Task<object> get_devices_db_taizhang()
        {
            Dictionary<string, string> statusDict = new Dictionary<string, string>
                {
                    { "run", "运行" },
                    { "fault", "故障" },
                    { "waiting", "待机" },
                    { "no", "未排产" },
                    { "other", "其他" }
                };
            var find_data3 = Db.Queryable<wsz_shebei>()
                    .ToList();
            return new
            {
                rows = find_data3,
                total = 1
            };
        }


        public async Task<object> get_dj_from_bfmes()
        {
            DateTime currentDate = DateTime.Today;
            // 获取前一天日期
            DateTime previousDate = currentDate.AddDays(-1);
            string currentDateStr1 = currentDate.ToString("yyyy-MM-dd") + " 16:00:00";
            string previousDateStr1 = previousDate.ToString("yyyy-MM-dd") + " 16:00:00";
            var find_data3 = Db.Queryable<wsz_shebei>()
                    .ToList();
            //Console.WriteLine(find_data3.)
            var final_data_info_ = new List<wsz_shebei>();
            for (int i = 0; i < find_data3.Count; i++)
            {
                ames.userName = "duyang@atmcn.com";
                ames.password = "Du123456*";
                ames.url = "http://10.7.1.17/jsonrpc";
                ames.db = "antai";
                var per_data = find_data3[i];
                Console.WriteLine((string)per_data.name);
                // 1. 构建domain条件树
                var domain1 = new List<object>
                {
                    "&",
                    new List<object> { "equipment_id", "ilike", (string)per_data.name },
                    "&",
                    new List<object> { "date", ">=", previousDateStr1},
                    new List<object> { "date", "<=", currentDateStr1 },
                };
                // 2. 构建specification字段映射
                var qFields = new List<string> {
                    "name"
                };
                // 3. 组合最终结构category_id
                var result = new Dictionary<string, object>
                {
                    { "domain", domain1 },
                    { "fields", qFields }
                };
                var resp = await ames.Get_web_search_read("maintenance.check", result);
                if (resp.ContainsKey("error"))
                {
                    var message = $"【拉取单据】{resp["error"].ToString()}";
                    throw new AppException(message);
                }
                var record = (JArray)resp["result"]["records"];
                Console.WriteLine(resp);
                string dj_detail = "";
                if ((int)resp["result"]["length"] > 0)
                {
                    dj_detail = "已点检";
                }
                else
                {
                    dj_detail = "";
                }
                int rowsAffected = Db.Updateable<wsz_shebei>()
                    .SetColumns(it => new wsz_shebei()
                    {
                        dj = dj_detail,
                    })
                    .Where(it => it.name == per_data.name) // 精确条件
                    .ExecuteCommand();
            }
            var Data = Db.Queryable<wsz_shebei>()
                .ToList();
            return Data;
        }


        public async Task<string> dianjian_wsz_devices(string shebei_type, int mesid)
        {
            ames.userName = "duyang@atmcn.com";
            ames.password = "Du123456*";
            ames.url = "http://10.7.1.17/jsonrpc";
            ames.db = "antai";

            var para_1 = new Dictionary<string, object>
                {
                    { "equipment_id", mesid }
                };
            var domain11 = new List<object>
                {
                    new List<object>(),
                    para_1,
                    "equipment_id",
                    new Dictionary<string, string>
                    {
                        {"equipment_id","1" },
                        {"maintenance_team_id",""},
                        {"user_id","" }
                    }
                };
            var resp1 = await ames.onchange("maintenance.check", domain11);
            Console.WriteLine(resp1);
            var result = resp1["result"]["value"];
            Console.WriteLine(result["maintenance_team_id"][0]);
            Console.WriteLine(result["user_id"][0]);
            var para_ = new Dictionary<string, object>
                {
                    { "equipment_id", mesid },
                    { "maintenance_team_id", result["maintenance_team_id"][0] },
                    { "user_id", result["user_id"][0] }
                };
            var domain1 = new List<object>
                {
                    para_
                };
            var resp = await ames.create("maintenance.check", domain1);
            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            var jd_order_id = resp["result"];
            Console.WriteLine(resp);
            Console.WriteLine(jd_order_id);
            try
            {
                var confirm = new List<object>
                {
                    new List<object> { jd_order_id }
                };
                var resp_confirm = await ames.button_done("maintenance.check", confirm, "button_done");
                int rowsAffected = Db.Updateable<wsz_shebei>()
                    .SetColumns(it => new wsz_shebei()
                    {
                        dj = "已点检",
                    })
                    .Where(it => it.mesid == mesid.ToString()) // 精确条件
                    .ExecuteCommand();
                return resp_confirm;
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("cannot marshal None"))
                {
                    Console.WriteLine("操作成功完成（服务端返回了None）");
                    // 执行后续操作
                }
                else
                {
                    // 重新抛出原始异常以保持堆栈跟踪
                    Console.WriteLine("这里的吗？？");

                }
                return "失败";
            }
        }



        public async Task<string> wb_wsz_devices(string shebei_type, int mesid, string wb_name)
        {
            ames.userName = "duyang@atmcn.com";
            ames.password = "Du123456*";
            ames.url = "http://10.7.1.17/jsonrpc";
            ames.db = "antai";
            var para_1 = new Dictionary<string, object>
                {
                    { "equipment_id", mesid }
                };
            var domain11 = new List<object>
                {
                    new List<object>(),
                    para_1,
                    "equipment_id",
                    new Dictionary<string, string>
                    {
                        {"equipment_id","1" },
                        {"maintenance_team_id",""},
                        {"user_id","" }
                    }
                };
            var resp1 = await ames.onchange("maintenance.request", domain11);
            var result = resp1["result"]["value"];
            var para_ = new Dictionary<string, object>
                {
                    { "name", wb_name },
                    { "equipment_id", mesid  },
                    { "user_id", result["user_id"][0]  }
                };
            var domain1 = new List<object>
                {
                   para_
                };
            var resp = await ames.create("maintenance.request", domain1);
            if (resp.ContainsKey("error"))
            {
                var message = $"【拉取单据】{resp["error"].ToString()}";
                throw new AppException(message);
            }
            try
            {
                int wb_id = 1;
                return "成功";
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("cannot marshal None"))
                {
                    Console.WriteLine("操作成功完成（服务端返回了None）");
                    // 执行后续操作
                }
                else
                {
                    // 重新抛出原始异常以保持堆栈跟踪
                    Console.WriteLine("这里的吗？？");

                }
                return "失败";
            }
        }


        public async Task<object> get_wb_from_bfmes()
        {
            var find_data3 = Db.Queryable<wsz_shebei>()
                    .ToList();
            //Console.WriteLine(find_data3.)
            var final_data_info_ = new List<object>();
            for (int i = 0; i < find_data3.Count; i++)
            {
                ames.userName = "duyang@atmcn.com";
                ames.password = "Du123456*";
                ames.url = "http://10.7.1.17/jsonrpc";
                ames.db = "antai";
                var per_data = find_data3[i];
                Console.WriteLine((string)per_data.name);
                // 1. 构建domain条件树
                var domain12 = new List<object>
                {
                    "&",
                    new List<object> { "equipment_id", "ilike", (string)per_data.name },
                    new List<object> { "stage_id", "not ilike", "已完成" },
                };
                // 2. 构建specification字段映射
                var qFields = new List<string> {
                    "id",
                    "name",
                    "equipment_id",
                    "work_order_id",
                    "request_date",
                    "schedule_date",
                    "employee_id",
                    "user_id",
                    "category_id",
                    "stage_id",
                };
                // 3. 组合最终结构category_id
                var result2 = new Dictionary<string, object>
                {
                    { "domain", domain12 },
                    { "fields", qFields }
                };
                var resp1 = await ames.Get_web_search_read("maintenance.request", result2);
                if (resp1.ContainsKey("error"))
                {
                    var message = $"【拉取单据】{resp1["error"].ToString()}";
                    throw new AppException(message);
                }
                var record1 = (JArray)resp1["result"]["records"];
                Console.WriteLine(resp1);
                final_data_info_.Add(record1);
            }
            return final_data_info_;
        }

        public async Task<string> wb_wsz_done_devices(string option_type, JArray done_type, int mesid, string wb_name)
        {
            ames.userName = "duyang@atmcn.com";
            ames.password = "Du123456*";
            ames.url = "http://10.7.1.17/jsonrpc";
            ames.db = "antai";
            var modles = "";
            Console.WriteLine(done_type);
            var result_id = 0;
            var domain1 = new List<object>();
            //domain1.Add(new List<object> { });
            if (option_type == "验收")
            {
                modles = "maintenance.request.check.wizard";
                if ((string)done_type[0]["acceptanceResult"] == "合格")
                {
                    domain1.Add(
                        new Dictionary<string, object>
                        {
                            {"check_state","qualified" },
                            {"request_id",mesid },
                            {"unqualified_reason",false }
                        }
                    );                    
                    
                }
            }
            else
            {
                modles = "maintenance.request.evaluation.wizard";
                if ((string)done_type[0]["evaluation"]["rating"] == "满意")
                {
                    domain1.Add(
                        new Dictionary<string, object>
                        {
                            {"evaluation_note","满意" },
                            {"evaluation_state","satisfy" },
                            {"request_id",mesid }
                        }
                    );
                }
            }
            var resp_1 = await ames.create(modles, domain1);
            try
            {
                var confirm = new List<object>
                {
                    new List<object> { (int)resp_1["result"] }
                };
                var resp_confirm = await ames.btn_confirm(modles, confirm, "button_done");
                if (resp_confirm == "成功")
                {
                    return "成功";
                }
                else
                {
                    return "失败";
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("cannot marshal None"))
                {
                    Console.WriteLine("操作成功完成（服务端返回了None）");
                    // 执行后续操作
                }
                else
                {
                    // 重新抛出原始异常以保持堆栈跟踪
                    Console.WriteLine("这里的吗？？");
                }
                return "失败";
            }
        }

        public class wsz_dev_type
        {
            [SugarColumn(IsPrimaryKey = true)] // 主键标识（若存在）
            public string device_name { get; set; }
            public string deta_type1 { get; set; }
            public string data_type2 { get; set; }
            //public string data_detail { get; set; }
            //public string mesid { get; set; }
            //public string dj { get; set; }

        }

        public class wsz_data_in
        {
            [SugarColumn(IsPrimaryKey = true)] // 主键标识（若存在）
            public string device_name { get; set; }
            public string data_name { get; set; }
            public string data_detail { get; set; }
            public string intime { get; set; }
            public string savetime { get; set; }
            public int Id { get; set; }
            //public string data_detail { get; set; }
            //public string mesid { get; set; }
            //public string dj { get; set; }

        }

        public async Task<object> get_base_data_in()
        {
            var find_data_type = Db.Queryable<wsz_dev_type>()
                    .ToList();
            var find_data_detail = Db.Queryable<wsz_data_in>()
                    .ToList();
            return new
            {
                find_data_type = find_data_type,
                find_data_detail = find_data_detail
            };
        }
        public async Task<object> delete_base_data_in(int id)
        {
            //var find_data_type = Db.Queryable<wsz_dev_type>()
            //        .ToList();
            //var find_data_detail = Db.Queryable<wsz_data_in>()
            //        .ToList();

            await Db.DoDeleteAsync<wsz_data_in>(x => x.Id == id, true);

            return "成功";

        }

        public async Task<string> base_data_input_detail(string option_type, JArray dataDetail)
        {
            Console.WriteLine("option_type", option_type);


            if (dataDetail == null)
            {
                throw new Exception("mes_data_final[1]不是有效的数组");
            }

            

            if(option_type == "新建")
            {
                // 2. 遍历二维数组中的每个子项
                var final_data_info1 = new List<wsz_data_in>();
                foreach (JArray item in dataDetail)
                {
                    var data_3 = new wsz_data_in
                    {
                        device_name = item[0].ToString(),
                        data_name = item[1].ToString(),
                        data_detail = item[2].ToString(),
                        intime = item[3].ToString(),
                        savetime = item[4].ToString()
                    };
                    // 提取子数组中的字符串元素（设备名、指标名、数值字符串、日期）
                    string device = item[0].ToString();       // "纯水机" 或 "前后处理水回用"
                    string indicator = item[1].ToString();    // "自来水量" 或 "回用水量"
                    string valueStr = item[2].ToString();     // "123" 或 "12"
                    string date = item[3].ToString();         // "2025-08-16"

                    // 3. 如需将数值字符串转为byte（需确保数值在0-255范围内）
                    if (byte.TryParse(valueStr, out byte valueByte))
                    {
                        Console.WriteLine($"设备：{device}，指标：{indicator}，数值（byte）：{valueByte}，日期：{date}");
                    }
                    else
                    {
                        Console.WriteLine($"设备：{device}，指标：{indicator}，数值（无法转为byte）：{valueStr}，日期：{date}");
                    }
                    final_data_info1.Add(data_3);
                }

                await Db.DoInsertAsync<wsz_data_in>(final_data_info1);
            }
            else
            {
                // 2. 遍历二维数组中的每个子项
                var final_data_info1 = new List<wsz_data_in>();
                foreach (JArray item in dataDetail)
                {
                    var data_3 = new wsz_data_in
                    {
                        device_name = item[0].ToString(),
                        data_name = item[1].ToString(),
                        data_detail = item[2].ToString(),
                        intime = item[3].ToString(),
                        savetime = item[4].ToString()
                    };
                    final_data_info1.Add(data_3);
                    int rowsAffected2 = Db.Updateable<wsz_data_in>()
                    .SetColumns(it => new wsz_data_in
                    {
                        device_name = item[0].ToString(),
                        data_name = item[1].ToString(),
                        data_detail = item[2].ToString(),
                        intime = item[3].ToString(),
                        savetime = item[4].ToString()
                    })
                    .Where(it => it.Id == (int)item[5]) // 精确条件
                    .ExecuteCommand();
                }

                //await Db.DoInsertAsync<wsz_data_in>(final_data_info1);
            }

            return "成功";
        }

        public async Task<object> search_base_data_all_api()
        {
            //var find_data_type = Db.Queryable<wsz_dev_type>()
            //        .ToList();
            //var find_data_detail = Db.Queryable<wsz_data_in>()
            //        .ToList();

            var find_data_type = Db.Queryable<wsz_dev_type>()
                    .ToList();
            var find_data_detail = Db.Queryable<wsz_data_in>()
                    .ToList();
            return new
            {
                find_data_type = find_data_type,
                find_data_detail = find_data_detail
            };

        }


        public async Task<object> get_db_get_db_eng(string at_step,string[] date_riqi_list, string[] zhou)
        {
            Console.WriteLine("进来了！！");
            // 查询数据库中当天最大的code
            // 使用 SqlSugar 的 Queryable 语法
            //string connectionString = "server=localhost;port=3306;database=biz_app;user=root;password=admin;";
            string connectionString = "Server=10.7.4.214;Port=3306;Database=imr_client;Uid=root;Pwd=12345678;";
            var final_data_info = new List<object>();
            //string query = @"
            //SELECT * 
            //FROM at_step 
            //WHERE item1 = @item1 
            //AND dr = @dr";
            ////var updater = new MaterialPlanUpdater1();
            ////updater.UpsertData(plan_data_final);
            //QueryAtStepData(connectionString);
            //QueryJune2025Data(connectionString);
            var final_data_info_ = new List<object>();
            for (int i = 0; i < (date_riqi_list.Length) / 2; i++)
            {
                
                string startTime_ = date_riqi_list[i * 2];
                string endtime = date_riqi_list[i * 2 + 1];
                string startTime = "";

                if (i == (date_riqi_list.Length/2)-1)
                {
                    startTime = GetResultTime(startTime_).ToString();
                }
                else
                {
                    startTime = startTime_;
                }

                Console.WriteLine(startTime);
                Console.WriteLine(endtime);
                var result = get_eng(connectionString, startTime, endtime,at_step);
                double result_data = 0.0;
                foreach (var val in result)
                {
                    Console.WriteLine(val);
                    result_data += Double.Parse(val);
                }
                final_data_info_.Add(Math.Round(result_data, 2));
            }
            var final_data_info1_ = new List<object>();
            for (int i = 0; i < final_data_info_.Count / 2; i++)
            {
                Console.WriteLine(final_data_info_[0]);
                double pei_ = (double)final_data_info_[i * 2 + 1];
                double pei_1 = (double)final_data_info_[i * 2];
                final_data_info1_.Add(Math.Round(pei_ - pei_1, 2));
            }
            for (int x = 0; x < final_data_info1_.Count; x++)
            {
                var zhou_ = zhou[x];
                var eng_data = final_data_info1_[x];
                var data_3 = new wsz_data_in
                {
                    device_name = "电镀污水处理耗电量",
                    data_name = "耗电量",
                    data_detail = eng_data.ToString(),
                    intime = zhou_,
                    //savetime = item[4].ToString()
                };
                int count1 = Db.Queryable<wsz_data_in>()
                    .Where(it => it.intime == (string)zhou_)
                    .Count();
                if(count1 == 0)
                {
                    await Db.DoInsertAsync<wsz_data_in>(data_3);
                }
                else
                {
                    int rowsAffected2 = Db.Updateable<wsz_data_in>()
                    .SetColumns(it => new wsz_data_in
                    {
                        data_detail = eng_data.ToString(),
                    })
                    .Where(it => it.intime == (string)zhou_) // 精确条件
                    .ExecuteCommand();
                }
                
            }


            return final_data_info_;
        }

        public String? GetResultTime(string targetTimeStr)
        {
            // 目标时间字符串
            //string targetTimeStr = "2025-09-07 23:00:00";
            // 定义时间格式（与字符串格式匹配）
            string timeFormat = "yyyy-MM-dd HH:mm:ss";

            // 尝试将字符串转换为DateTime类型（避免格式错误导致异常）
            if (!DateTime.TryParseExact(
                targetTimeStr,
                timeFormat,
                CultureInfo.InvariantCulture,  // 固定文化格式，避免地区差异影响解析
                DateTimeStyles.None,
                out DateTime targetTime))
            {
                Console.WriteLine("时间字符串格式不正确，无法解析");
                return null;
            }

            // 获取当前本地时间
            DateTime currentTime = DateTime.Now;

            Console.WriteLine($"当前时间：{currentTime:yyyy-MM-dd HH:mm:ss}");
            Console.WriteLine($"目标时间：{targetTime:yyyy-MM-dd HH:mm:ss}");

            // 判断当前时间是否小于目标时间
            if (currentTime < targetTime)
            {
                // 计算当前整点时间（例如：10:05:30 → 10:00:00）
                DateTime currentWholeHour = new DateTime(
                    currentTime.Year,
                    currentTime.Month,
                    currentTime.Day,
                    currentTime.Hour,  // 保留当前小时
                    0,  // 分钟设为0
                    0   // 秒设为0
                );

                // 计算当前时间与当前整点的时间差
                TimeSpan timeDiff = currentTime - currentWholeHour;
                Console.WriteLine($"当前时间与当前整点({currentWholeHour:HH:mm:ss})的差值：{timeDiff.TotalMinutes:F2}分钟");

                DateTime resultTime;
                // 判断差值是否超过1分钟（60秒）
                if (timeDiff.TotalMinutes > 1)
                {
                    // 超过1分钟 → 使用当前整点时间
                    resultTime = currentWholeHour;
                    Console.WriteLine("当前时间比当前整点多1分钟以上，使用当前整点时间");
                }
                else
                {
                    // 未超过1分钟 → 使用前一小时的整点时间
                    resultTime = currentWholeHour.AddHours(-1);
                    Console.WriteLine("当前时间比当前整点多1分钟以内，使用前一小时的整点时间");
                }

                Console.WriteLine($"最终选择的整点时间：{resultTime:yyyy-MM-dd HH:mm:ss}");
                return resultTime.ToString(timeFormat);
            }
            else
            {
                Console.WriteLine("当前时间不小于目标时间，无需计算前一小时");
                return targetTimeStr;  // 或返回当前时间，根据实际需求调整
            }
        }
        public List<string> get_eng(string connect_string, string startTime, string endtime,string pkStep)
        {
            // 存储结果的集合
            var result = new List<string>();

            // 数据库连接字符串（请替换为你的实际连接信息）
            string connectionString = connect_string;
            
            // SQL语句，使用@pkStep作为参数占位符
            string sql = @"
            SELECT ade.vriable_value_now,ade.vriable_code 
            FROM `at_data_energy` ade
            JOIN `at_device` ad ON ade.pk_device = ad.pk
            WHERE ad.pk_step = @pkStep  
              AND ad.dr = 0
              AND ade.inputtime > @startTime
              AND ade.inputtime < @endtime;";

            using (var connection = new MySqlConnection(connectionString))
            {
                using (var command = new MySqlCommand(sql, connection))
                {
                    // 添加参数（关键：防止SQL注入）
                    command.Parameters.AddWithValue("@pkStep", pkStep);
                    command.Parameters.AddWithValue("@startTime", startTime);
                    command.Parameters.AddWithValue("@endtime", endtime);
                    Console.WriteLine(sql);
                    try
                    {
                        connection.Open();
                        using (var reader = command.ExecuteReader())
                        {
                            // 读取查询结果
                            while (reader.Read())
                            {
                                // 假设vriable_value_now是字符串类型，根据实际类型调整
                                if(reader["vriable_code"].ToString() == "IP212_2_M_2AA7_4_KWH" || reader["vriable_code"].ToString() == "IP213_2_M_3AA8_2_KWH")
                                {
                                    Console.WriteLine("");
                                }
                                else
                                {
                                    string value = reader["vriable_value_now"].ToString();
                                    result.Add(value);
                                }
                                
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        // 处理异常（如日志记录、错误提示等）
                        Console.WriteLine($"查询出错：{ex.Message}");
                        throw; // 按需决定是否向上抛出异常
                    }
                }
            }
            
            return result;
        }
    }
}
